package com.boot.controller;


import com.boot.DAO.OrderDAO;
import com.boot.init.StockRepository;
import com.boot.pojo.Product;
import com.boot.result.Result;
import com.boot.scripts.LuaScriptLoader;
import com.boot.service.OrderService;
import com.boot.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private StockRepository stockRepository;
    @Autowired
    private ProductService productService;
    @Autowired
    private LuaScriptLoader luaScriptLoader;

    @PostMapping("init")
    public String initStock() {
        List<Product> productList = productService.getProductList();
        if (productList != null && !productList.isEmpty()) {
            Map<String, String> stockMap = new HashMap<String, String>();
            for (Product product : productList) {
                stockMap.put("product:stock:" + product.getId(), String.valueOf(product.getStock()));
            }
            stockRepository.initStock(stockMap);
        }
        return "库存初始化成功";
    }

    @PostMapping("buy")
    public Result buy(@RequestBody OrderDAO orderDao) {
        try {
            return orderService.createOrder(
                    orderDao.getProductId(),
                    orderDao.getQuantity(),
                    orderDao.getUserId()
            );
        } catch (Exception e) {
            return Result.build(100010, "async error", e.getMessage());
        }

    }
}
